<template>
  <div>
    <!--导航栏 -->
    <van-nav-bar title="登录" />

    <!--表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="user.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          loading-text="登录中..."
          :loading="loading"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from "@/api";
export default {
  data() {
    return {
      //控制登录按钮的加载状态
      loading: false,
      user: {
        //双向绑定内容
        mobile: "",
        code: "",
      },
      //规则对象
      rules: {
        mobile: [
          { required: true, message: "请填写验证码" },
          { pattern: /^1[2-9]\d{9}$/, message: "请输入正确手机号" },
        ],
        code: [
          { required: true, message: "请填写验证码" },
          { pattern: /^\d{6}$/, message: "请输入6位数字验证码" },
        ],
      },
    };
  },
  methods: {
    // onSubmit() {
    //   //先加载显示
    //   this.loading = true;
    //   loginAPI(this.user)
    //     .then((res) => {
    //       console.log(res);
    //       this.$toast.success("登录成功!");
    //     })
    //     .catch((error) => {
    //       //   console.log('登录失败');
    //       this.$toast.fail("登录失败!");
    //     })
    //     .finally(() => {
    //       this.loading = false;
    //     });
    // },
    async onSubmit() {
      this.loading = true;
      //使用await后如果捕捉错误，就要配合try里的代码会从上往下依次执行，如果没报错，
      // 就不会进到catch里，如果报错了那么就会进到catch，哪句报错就从哪句进来
      try {
        let res = await loginAPI(this.user);
        console.log(res);
        this.$toast.success("登录成功");

        // 把得到的vuex保存到vuex里以及保存到本地存储
        this.$store.commit("setToken", res.data.data);

        // 判断有没有参数
        if (this.$route.query.back) {
          // 要么跳转到我原本想访问的页面
          this.$router.push(this.$route.query.back);
        } else {
          // 跳转到首页
          this.$router.push("/layout/home");
        }
      } catch {
        this.$toast.fail("登录失败");
      }

      this.loading = false;
    },
  },
};
</script>

<style></style>
